﻿using System;
using System.Linq;
using System.IO;
using Diploma.Models.IRepositories;
using Diploma.Models.Utils;

namespace Diploma.Models.Repositories
{
    internal class NormControlDocsRepository : INormControlDocsRepository
    {
        private readonly DiplomaEntities _dataContext;

        public NormControlDocsRepository(DiplomaEntities dataContext) 
        {
            _dataContext = dataContext;
        }

        public NormControlDoc GetDoc(Guid id)
        {
            return _dataContext.NormControlDocs.FirstOrDefault(d=>d.NormControlDocId == id);
        }

        public void Add(System.Web.HttpPostedFileBase postFile, Student student)
        {            
            string tempDocFile = Path.GetTempFileName();
            string tempPdfFile = Path.GetTempFileName();
            
            postFile.SaveAs(tempDocFile);
            WordUtil.ConvertFromDocToPdf(tempDocFile, tempPdfFile);

            NormControlDoc newDoc = new NormControlDoc()
            {
                NormControlDocId = Guid.NewGuid(),
                IsPassed = false,
                DateSanded = DateTime.Now,
                FileName = Path.GetFileName(postFile.FileName),
                DocFile = File.ReadAllBytes(tempDocFile),
                PdfFile = File.ReadAllBytes(tempPdfFile),
                Student = student,                
            };

            _dataContext.SaveChanges();
            
            File.Delete(tempDocFile);
            File.Delete(tempPdfFile);
        }

        public void SetCompletion(NormControlDoc doc, bool isPassed)
        {
            doc.IsPassed = isPassed;
            _dataContext.SaveChanges();
        }
    }
}